package com.esoon.activity;


import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.esoon.smartsee.R;
import com.esoon.utils.CameraUtils;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;


import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;


public class FaceRecognizeActivity extends AppCompatActivity {
    private static final String TAG = "PlayActivity";
    private SurfaceView surfaceView;
    private CameraUtils cameraUtils;
    private String path, name;
    private ImageButton btn;
    private ImageButton camera;
    private ImageButton change;
    private ImageView peronviw;
    private ImageButton backToMain;
    private TextView recognizeText;
    private SharedPreferences sp;
    private JSONObject jsonObject;
    private String userName = "mcu";
    private String passWord = "bnp@1234";
    private String hostName = "47.103.45.89";
    private int portNum = 60000;
    private String exchangeName = "amq.direct";
    int x = 0;
    static Handler handler;
    private String userId;
    private SharedPreferences sharedPreferences;
    private final static String EXCHANGE = "amq.direct";//topic绫诲瀷浜ゆ崲鍣�
    private final static String QUEUE1 = "queue_";
    private final static String ROUTING_KEY1 = "key_";
    private SharedPreferences.Editor editor;
    private Thread uploadthread;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_camera);
        if (sharedPreferences == null) {

            sharedPreferences = getSharedPreferences("smartsee", MODE_PRIVATE);
        }

        userId = sharedPreferences.getString("userName", "");
        editor = sharedPreferences.edit();

        uploadthread = new Thread(() -> {
            basicConsume();
        });

        uploadthread.start();
        /* new Thread(() -> {
            basicPublish();
        }).start();*/
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case 10:
                      //  Toast.makeText(FaceRecognizeActivity.this, "上传图片成功", Toast.LENGTH_LONG).show();
                        //cameraUtils.startpreview();
                      /*  Intent intent = new Intent(FaceRecognizeActivity.this, FaceFailActivity.class);
                        startActivity(intent);*/
                        //  finish();

                        break;

                    case 1:
                       // Toast.makeText(FaceRecognizeActivity.this, msg.obj + "", Toast.LENGTH_LONG).show();
                        break;

                    case 2:

                        JSONObject jsonObject = new JSONObject();
                        jsonObject = (JSONObject) msg.obj;
                        try {
                            editor.putString("picId", jsonObject.getString("face0_id"));
                            editor.commit();

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        Log.e(TAG,sharedPreferences.getString("picId",""));
                       // Toast.makeText(FaceRecognizeActivity.this, "识别结果是:" + msg.obj + "", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(FaceRecognizeActivity.this, FaceComfireActivity.class);
                        startActivity(intent);
                        finish();
                        break;

                    case 7:

                       // Toast.makeText(FaceRecognizeActivity.this, "识别结果是:" + msg.obj + "", Toast.LENGTH_LONG).show();
                        Intent intent1 = new Intent(FaceRecognizeActivity.this, FaceFailActivity.class);
                        startActivity(intent1);
                        finish();
                        break;

                    case 3:

                       // Toast.makeText(FaceRecognizeActivity.this, "识别结果是:" + msg.obj + "", Toast.LENGTH_LONG).show();
                        Intent intent2 = new Intent(FaceRecognizeActivity.this, FaceFailActivity.class);
                        startActivity(intent2);
                        finish();
                        break;

                    case 4:

                      //  Toast.makeText(FaceRecognizeActivity.this, "识别结果是:" + msg.obj + "", Toast.LENGTH_LONG).show();
                        Intent intent3 = new Intent(FaceRecognizeActivity.this, FaceFailActivity.class);
                        startActivity(intent3);
                        finish();
                        break;
                    case 5:

                      //  Toast.makeText(FaceRecognizeActivity.this, "识别结果是:" + msg.obj + "", Toast.LENGTH_LONG).show();
                        Intent intent4 = new Intent(FaceRecognizeActivity.this, FaceFailActivity.class);
                        startActivity(intent4);
                        finish();
                        break;
                    case 6:

                        //Toast.makeText(FaceRecognizeActivity.this, "识别结果是:" + msg.obj + "", Toast.LENGTH_LONG).show();
                        Intent intent5 = new Intent(FaceRecognizeActivity.this, FaceFailActivity.class);
                        startActivity(intent5);
                        finish();
                        break;
                    case 8:

                       // Toast.makeText(FaceRecognizeActivity.this, "识别结果是:" + msg.obj + "", Toast.LENGTH_LONG).show();
                        Intent intent6 = new Intent(FaceRecognizeActivity.this, FaceFailActivity.class);
                        startActivity(intent6);
                        finish();
                        break;
                    case 9:

                       // Toast.makeText(FaceRecognizeActivity.this, "识别结果是:" + "匹配度小于70" + "", Toast.LENGTH_LONG).show();
                        Intent intent7 = new Intent(FaceRecognizeActivity.this, FaceFailActivity.class);
                        startActivity(intent7);
                        finish();
                        break;
                }
            }
        };
        Log.d(TAG, "onCreate: ");
        // getSupportActionBar().hide();
        if (sp == null) {

            sp = getSharedPreferences("smartsee", Activity.MODE_PRIVATE);
        }
        recognizeText = findViewById(R.id.recognizeText);
        backToMain = findViewById(R.id.backToMain);
        peronviw = findViewById(R.id.person_img);
        //  btn = (ImageButton) findViewById(R.id.camera_vedio);
        //   camera = (ImageButton) findViewById(R.id.camera_photo);
        change = findViewById(R.id.switchCamera);
        surfaceView = findViewById(R.id.camera_surfaceview);

        cameraUtils = new CameraUtils();
        cameraUtils.create(surfaceView, this);
        //  cameraUtils.changeCamera();
        path = Environment.getExternalStorageDirectory().getAbsolutePath();
        name = "Video";

        backToMain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
       /* camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });*/

        change.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cameraUtils.changeCamera();
            }
        });

        peronviw.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                peronviw.setClickable(false);
                recognizeText.setText("正在识别中，请稍后");
                cameraUtils.takePicture(path, "name.png", surfaceView, peronviw, sp.getString("userName", ""), handler);
                Log.e("用户id 是：", sp.getString("userName", ""));
            }
        });

       /* btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cameraUtils.startpreview();
            }
        });*/
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "onResume: ");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "onPause: ");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "onStop: ");
        cameraUtils.stop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy: ");
        cameraUtils.destroy();

    }


    private void basicPublish() {

        try {
            //连接

            ConnectionFactory factory;
            factory = new ConnectionFactory();
            factory.setHost(hostName);//ip地址
            factory.setPort(portNum);//端口号
            factory.setUsername(userName);
            factory.setPassword(passWord);
            factory.setVirtualHost("vms");
            Connection connection;
            Channel channel;
            connection = factory.newConnection();
            //通道
            channel = connection.createChannel();
            //消息发布
            byte[] msg = "hello girl friend!".getBytes();
            //rountingKey 自己任意填写
            channel.queueDeclare("queue_" + userId, false, false, false, null);
            channel.basicPublish(exchangeName, "key_" + userId, null, msg);

            Log.e(TAG, "sending msg");
            channel.close();
            connection.close();

        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }

    }

    private void basicConsume() {

        System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!1");
        ConnectionFactory factory = new ConnectionFactory();
        Connection connection = null;

        try {
            factory.setPort(Integer.parseInt(sharedPreferences.getString("mqPort", "")));
            factory.setHost(sharedPreferences.getString("mqServer", ""));
            factory.setUsername(sharedPreferences.getString("mqName", ""));
            factory.setPassword(sharedPreferences.getString("mqPsd", ""));
            factory.setVirtualHost("vms");
            connection = factory.newConnection();
            //鍒涘缓杩炴帴
            System.out.println(1111);
            final Channel channel = connection.createChannel();
            //澹版槑浜ゆ崲鍣ㄩ槦鍒楃粦瀹氱瓑淇℃伅
            System.out.println(2222);
            //channel.exchangeDeclare(EXCHANGE, TYPE, true);
            channel.queueDeclare(QUEUE1 + userId, false, false, false, null);
            channel.queueBind(QUEUE1 + userId, EXCHANGE, ROUTING_KEY1 + userId);
            System.out.println(444);


            Consumer critical_notify = new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    System.out.println(consumerTag);
                    String message = new String(body, "UTF-8");
                    try {
                        jsonObject = new JSONObject(message);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    System.out.println("Customer Received '" + message + "'");
                 /*   String subject = "Critical Alert";
                    String msg = new String(body,"UTF-8");*/
                    Message message1 = new Message();
                    try {
                        if (jsonObject.getInt("status") == 0) {
                            if (jsonObject.getInt("confidence") >= 70) {

                                message1.what = 2;
                                message1.obj=jsonObject;
                            } else {
                                message1.what = 9;

                            }

                        } else if (jsonObject.getInt("status") == -1) {
                            message1.what = 3;
                            message1.obj = "No accessid/key";
                        } else if (jsonObject.getInt("status") == -2) {
                            message1.what = 4;
                            message1.obj = "No original face";

                        } else if (jsonObject.getInt("status") == -3) {
                            message1.what = 5;
                            message1.obj = "No original face file";

                        } else if (jsonObject.getInt("status") == -4) {
                            message1.what = 6;
                            message1.obj = "Failed to process face";

                        } else if (jsonObject.getInt("status") == -5) {
                            message1.what = 7;
                            message1.obj = "校验失败";
                        } else if (jsonObject.getInt("status") == -6) {
                            message1.what = 8;
                            message1.obj = "Face verify exception";

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    handler.sendMessage(message1);

                    channel.basicAck(envelope.getDeliveryTag(), false);
                }
            };
            //娑堟伅娑堣垂
            channel.basicConsume(QUEUE1 + userId, false, "critical", critical_notify);
            System.out.println("mq连接结果是:" + channel.isOpen());
            //  channel.basicConsume(QUEUE2,false,"rate_limit",rate_limit_notify);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }
}